package com.rc.saas.mini.controller.order;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rc.saas.base.MinipBaseController;
import com.rc.saas.mini.common.base.DataTResponse;
import com.rc.saas.mini.common.mq.MqConfig;
import com.rc.saas.mini.common.mq.MqProducer;
import com.rc.saas.mini.minip.vo.LoginInfoVo;
import com.rc.saas.mini.model.order.OrderInfo;
import com.rc.saas.mini.model.order.OrderRefundApply;
import com.rc.saas.mini.model.order.OrderRefundApplyExample;
import com.rc.saas.mini.model.rc.RcMsgNotification;
import com.rc.saas.mini.service.order.OrderInfoService;
import com.rc.saas.mini.service.order.OrderRefundApplyService;
import com.rc.saas.mini.service.rc.RcMsgNotificationService;
import com.rc.saas.mini.vo.base.RcPageVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

/**
 * @Description
 * @Author
 * @Date: 2022-06-01
 */

@Api(tags = "20.订单退款申请")
@Controller
@RequestMapping("/orderRefundApply")
public class OrderRefundApplyController extends MinipBaseController {

    private static Logger logger = LogManager.getLogger(OrderRefundApplyController.class);
    @Autowired
    private OrderRefundApplyService orderRefundApplyService;

    @Autowired
    private MqProducer mqProducer;
    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private RcMsgNotificationService rcMsgNotificationService;


    @ResponseBody
    @RequestMapping(value="/refundApply",method = RequestMethod.POST)
    @ApiOperation(value = "退款申请", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    public DataTResponse<String> refundApply(HttpServletRequest request, OrderRefundApply orderRefundApply) {

        LoginInfoVo loginInfo = readLoginInfo(request);
        if (loginInfo == null || loginInfo.getMemberId() == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        if (orderRefundApply.getOrderId() == null || orderRefundApply.getAmount() == null) {
            return DataTResponse.FAIL("订单id/金额不能为空");
        }
        OrderRefundApplyExample example = new OrderRefundApplyExample();
        example.createCriteria().andOrderIdEqualTo(orderRefundApply.getOrderId());
        example.setOrderByClause("last_updated_time desc,created_time desc");
        List<OrderRefundApply> oldList = orderRefundApplyService.selectByExample(example);
        if (oldList != null && oldList.size() > 0
                && oldList.stream()
                .filter(data -> "0".equals(data.getStatus()) || "1".equals(data.getStatus())).findFirst().orElseGet(() -> null) != null) {
            return DataTResponse.FAIL("订单已申请!");
        }

        OrderInfo orderInfo=orderInfoService.selectOrderById(orderRefundApply.getOrderId());

        String tenantCode = loginInfo.getTenantCode();
        orderRefundApply.setOrderRefundApplyId(null);
        orderRefundApply.setTenantCode(tenantCode);
        orderRefundApply.setMemberId(loginInfo.getMemberId());
        if(orderRefundApply.getAmount()!=null&&orderRefundApply.getAmount().compareTo(orderInfo.getPayAmount())>0){
            return DataTResponse.FAIL("退款金额要等于订单实付金额!");
        }
        orderRefundApply.setFactAmount(orderInfo.getPayAmount());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String timeStamp = dateFormat.format(System.currentTimeMillis());
        String num = "R" + timeStamp + StringUtils.right(UUID.randomUUID().toString(), 4);
        orderRefundApply.setOrderNum(num);
        orderRefundApply.setAmount(orderInfo.getPayAmount());
        orderRefundApply.setCreatedTime(new Date());
        orderRefundApply.setStatus("0");
        orderRefundApplyService.insertByReturnId(orderRefundApply);

        HashMap<String, Long> map = new HashMap<>();
        map.put("orderRefundApplyId", orderRefundApply.getOrderRefundApplyId());
        //todo 发送mq 给后台
        mqProducer.send(MqConfig.platform_apply, JSON.toJSONString(map));

        RcMsgNotification rcMsgNotification = new RcMsgNotification();
        rcMsgNotification.setTenantCode(loginInfo.getTenantCode());
        rcMsgNotification.setMsgType("3");
        rcMsgNotification.setMsgId(orderRefundApply.getOrderRefundApplyId().toString());
        rcMsgNotificationService.saveRcMsgNotification(rcMsgNotification);

        return DataTResponse.SUCCESS();
    }

    @ResponseBody
    @RequestMapping(value = "/refundApplyDetail",method = RequestMethod.POST)
    @ApiOperation(value = "退款申请明细", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderRefundApplyId", paramType = "query", value = "申请id", required = false)})
    public DataTResponse<OrderRefundApply> refundApply(HttpServletRequest request, Long orderRefundApplyId) {

        LoginInfoVo loginInfo = readLoginInfo(request);
        if (loginInfo == null || loginInfo.getMemberId() == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        OrderRefundApply orderRefundApply = new OrderRefundApply();
        orderRefundApply.setMemberId(loginInfo.getMemberId());
        orderRefundApply.setOrderRefundApplyId(orderRefundApplyId);
        return DataTResponse.SUCCESS_DATA(orderRefundApplyService.listByCondition(orderRefundApply).stream().findFirst().orElseGet(() -> null));
    }


    /**
     * 查询列表分页
     */
    @ApiOperation("查询列表分页 订单退款申请")
    @RequestMapping(value = "/listPageByOrderRefundApply", method = RequestMethod.POST)
    @ResponseBody
    private DataTResponse<PageInfo<OrderRefundApply>> listPageByOrderRefundApply(HttpServletRequest request, RcPageVo rcPageVo) {
        OrderRefundApply orderRefundApply = new OrderRefundApply();
        LoginInfoVo loginInfo = readLoginInfo(request);
        if (loginInfo == null || loginInfo.getMemberId() == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        orderRefundApply.setMemberId(loginInfo.getMemberId());
        //Page
        PageHelper.startPage(rcPageVo.getPageNo(), rcPageVo.getPageSize());
        List<OrderRefundApply> list = orderRefundApplyService.listByCondition(orderRefundApply);
        PageInfo<OrderRefundApply> pageInfo = new PageInfo<>(list);
        return DataTResponse.SUCCESS_DATA(pageInfo);
    }
}
